<template>
  <el-dialog v-el-drag-dialog title="选择用户" width="1200px" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose" destroy-on-close>
    <div style="height: calc(85vh - 135px)">
      <split-pane :min-percent='10' :default-percent='20' split="vertical">
        <template slot="paneL">
          <el-card class="m-l-5">
            <el-input v-model="filterDeptText" class="m-b-20" placeholder="搜索机构" />
            <el-tree
              ref="deptTree"
              node-key="id"
              :data="treeData"
              :props="treeProps"
              :filter-node-method="filterDeptNode"
              class="filter-tree"
              default-expand-all
              highlight-current
              :expand-on-click-node="false"
              check-on-click-node
              @node-click="selectDept"
            />
          </el-card>
        </template>

        <template slot="paneR">
          <!-- 搜索区域 -->
          <el-card style="margin:0 0 5px 5px" v-show="showSearch">
            <el-form ref="queryForm" :inline="true" :model="queryData">
              <el-form-item prop="Q_loginName_S_LK">
                <el-input v-model="queryData.Q_loginName_S_LK" placeholder="登录名称" />
              </el-form-item>
              <el-form-item prop="Q_userName_S_LK">
                <el-input v-model="queryData.Q_userName_S_LK" placeholder="用户名称" />
              </el-form-item>
              <el-form-item prop="Q_email_S_LK">
                <el-input v-model="queryData.Q_email_S_LK" placeholder="邮箱" />
              </el-form-item>
              <el-form-item prop="Q_mobile_S_LK">
                <el-input v-model="queryData.Q_mobile_S_LK" placeholder="手机号" />
              </el-form-item>
              <el-form-item class="fr p-r-10">
                <el-button class="filter-item m-l-10" type="primary" round icon="el-icon-search" @click="handleFilter">
                  搜索
                </el-button>
                <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
                  清空
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- table区域 -->
          <el-card class="m-l-5">
            <el-row class="m-b-5" type="flex">
              <span class="m-r-10">已选人员:</span>
              <div class="m-r-5" v-for="person in selectionData" :key="person.userId">
                <el-tag type="info">{{ person.userName }}</el-tag>
              </div>
            </el-row>
            <el-row class="m-b-5" :gutter="10">
              <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
              <div class="top-right-btn m-r-10">
                <el-row>
                  <el-button size="mini" plain type="primary" icon="el-icon-check" @click="handleConfirm()">
                    保存
                  </el-button>
                  <el-button v-if="selectionData.length > 0" size="mini" plain type="info" icon="el-icon-refresh" @click="handleClearSelected()">
                    清空已选
                  </el-button>
                </el-row>
              </div>
            </el-row>
            <el-table
              ref="user_table"
              v-loading="tableLoading"
              :data="tableData"
              element-loading-text="加载中"
              border
              fit
              highlight-current-row
              show-overflow-tooltip
              height="300px"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange"
              @current-change="handleRadioChange"
            >
              <el-table-column v-if="!single" type="selection" width="32" />&nbsp;
              <el-table-column v-if="single" width="32">
                <template slot-scope="scope">
                  <el-radio
                    v-model="selectRadio"
                    :label="scope.row.userId"
                  >&nbsp;
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column align="center" label="登录名" prop="loginName" sortable width="100" show-overflow-tooltip />
              <el-table-column align="center" label="用户名" prop="userName" sortable width="120" show-overflow-tooltip />
              <el-table-column align="center" label="部门" prop="deptName" width="100" show-overflow-tooltip />
              <el-table-column align="center" label="性别" prop="gender" sortable width="75">
                <template slot-scope="scope">
                  <el-tag :type="getDictType('gender', scope.row.gender)" v-text="getDictValue('gender', scope.row.gender)" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="邮箱" prop="email" show-overflow-tooltip />
              <el-table-column align="center" label="手机" prop="mobile" show-overflow-tooltip />
            </el-table>

            <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData(false)" />
          </el-card>
        </template>
      </split-pane>
    </div>
  </el-dialog>
</template>

<script>
import { userTable } from '@/api/system/user'
import { deptTreeData } from '@/api/system/dept'
import SplitPane from 'vue-splitpane'

export default {
  name: 'UserTableDialog',
  components: {
    SplitPane
  },
  props: {
    appendToBody: {
      type: Boolean,
      default: true
    },
    single: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      filterDeptText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      showSearch: true,
      queryData: {
        Q_deptId_S_EQ: undefined,
        Q_loginName_S_LK: undefined,
        Q_userName_S_LK: undefined,
        Q_email_S_LK: undefined,
        Q_mobile_S_LK: undefined,
        Q_status_S_EQ: '0'
      },
      optionOfGender: [],
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectRadio: undefined,
      selectionData: [],
      skipSelectionChange: false
    }
  },
  watch: {
    filterDeptText(val) {
      this.$refs.deptTree.filter(val)
    }
  },
  methods: {
    init() {
      this.$nextTick(() => {
        this.getDictData()
        this.getTreeData()
        this.getTableData(true)
        this.visible = true
      })
    },
    getDictData() {
      this.$dictGroup('sys_user_sex').then(response => {
        this.optionOfGender = response
      }).catch(e => {})
    },
    getDictType(property, value) {
      return this.$api.getDictElement(this.optionOfGender, value)[2]
    },
    getDictValue(property, value) {
      return this.$api.getDictElement(this.optionOfGender, value)[1]
    },
    filterDeptNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    selectDept(data, node) {
      this.queryData.Q_deptId_S_EQ = data.id
      this.handleFilter()
    },
    getTreeData() {
      deptTreeData({
        from: 'vue'
      }).then(response => {
        this.treeData = response
      }).catch(e => {})
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData(false)
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData(true)
    },
    getTableData(skipSelectionChane) {
      this.skipSelectionChange = skipSelectionChane
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      userTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.skipSelectionChange = false
        this.$refs.user_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
        this.skipSelectionChange = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleRadioChange(row) {
      if (row && this.single) {
        this.selectionData = []
        this.selectionData.push(row)
      }
    },
    handleSelectionChange(selection) {
      if (selection && !this.skipSelectionChange) {
        this.selectionData = this.selectionData.filter(data => {
          let result = false
          selection.forEach(row => {
            if (data.userId === row.userId) {
              result = true
            }
          })
          return result
        })
        this.selectionData = this.selectionData.concat(selection)
      }
    },
    handleConfirm() {
      if (this.selectionData.length === 0 && this.selectRadio === undefined) {
        this.$modal.msgWarning('请至少选择一项')
        return
      }
      if (this.single) {
        const selected = this.tableData.filter(row => {
          return row.userId === this.selectRadio
        })
        this.$emit('confirmDialog', selected)
      } else {
        this.$emit('confirmDialog', this.selectionData)
      }

      this.onClose()
    },
    handleClearSelected() {
      this.selectRadio = undefined
      this.skipSelectionChange = true
      this.$refs.user_table.clearSelection()
      this.selectionData = []
      this.skipSelectionChange = false
    },
    onClose() {
      this.$refs.queryForm.resetFields()
      this.handleClearSelected()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-tree {
  overflow-y: auto;
}

.filter-tree {
  height: calc(100vh - 370px);
}
</style>
